const jwt = require('jsonwebtoken');
const config = require('../config/config');
const { sendError } = require('../utils/response');

module.exports = {
  // 验证JWT
  authenticate: (req, res, next) => {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (!token) {
      return sendError(res, '未提供认证令牌', 401);
    }

    try {
      const decoded = jwt.verify(token, config.jwtSecret);
      req.user = decoded;
      next();
    } catch (err) {
      sendError(res, '无效的认证令牌', 401);
    }
  },

  // 检查用户角色
  authorize: (roles) => (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return sendError(res, '无权访问此资源', 403);
    }
    next();
  },

 
};